require([ 'jquery', 'common', 'producttype', 'validate','timepicker', 'pagination', 'bootstrap', 'dateZh','plupload','T_upload'], 
		function($, common,producttype, validate,timepicker,T_upload) {
	
	//日期控件
	$('#date-start, #date-end').datetimepicker({
		format : "yyyy-mm-dd hh:ii:ss",
		language : "zh-CN",
		todayBtn : 1,
		autoclose : true,
		todayHighlight : true,
		forceParse : true,
		minuteStep : 10
	});
	
	var addr = new producttype.ProductType({
		wrapper: $('.address-group'),
		firstlevelWrapper: $('#provinceQuery'),
		secondlevelWrapper: $('#cityQuery'),
		thiredlevelWrapper: $('#countyQuery'), 
	});  
	
	var first_load = true;
	var reload = true; 
	
	$(document).ready(function() {
		showProductBrand(); 
		$("#productAttrDiv").hide();
	});
	
	//placeholder兼容ie start
	$(function() {
		if (!placeholderSupport()) { // 判断浏览器是否支持 placeholder
			$('[placeholder]').focus(function() {
				var input = $(this);
				if (input.val() == input.attr('placeholder')) {
					input.val('');
					input.removeClass('placeholder');
				}
			}).blur(function() {
				var input = $(this);
				if (input.val() == ''
						|| input.val() == input.attr('placeholder')) {
					input.addClass('placeholder');
					input.val(input.attr('placeholder'));
				}
			}).blur();
		};
		
		showProductByPage(1);
		$("#updateImgIds").val('');
	});
	function placeholderSupport() {
		return 'placeholder' in document.createElement('input');
	}
	//placeholder兼容ie end

	//清除按钮
	$('.clearBtn').on('click', function() {
		$('.setTableLength').val(10);
		$("#productName").val(''),
		$("#barCode").val(''),
		$("#code").val(''),
		$("select[name='shelveState']").val(''),
		$("select[name='auditState']").val(''),
		$("select[name='tradeType']").val(''),
		$("#date-start").val('');
		$("#date-end").val('');
	});
	
	$(".setTableLength").change(function() {
		reload = true;
		showProductByPage(1);
	});

	$(".searchBtn").click(function() {
		reload = true;
		showProductByPage(1);
	});
	
	/** 列表查询start **/
	function showProductByPage(pageNum) {
		if ($(".all").is(':checked')) {
			$(".all").removeAttr('checked');								
		}	
		if($('.alert-warning').length>0){
    		$('.alert-warning').remove();
    	}
		$.getJSON(ctx + '/product/showproductbypage', {	
				pageNum : pageNum,
				pageSize : $('.setTableLength').val() || 10,
				startTime : $("#date-start").val(),
				endTime : $("#date-end").val(),	
				productName : $("#productName").val(),
				barCode : $("#barCode").val(),
				code : $("#code").val(),
				shelveState : $("select[name='shelveState']").val(),
				auditState : $("select[name='auditState']").val(),
				tradeType : $("select[name='tradeType']").val()
			},
			function(data){  
				if($('.loading')){
					$('.loading').remove();
				}
				var result = data.result;
				if(result!=null && result=="noauthority") {
					common.alert1('你无此权限!');
					return;
				}
				if(data.result!=null && data.result=="againLogin") {
					common.alert1("登录过期，请重新登录");
						setTimeout("location.href = ctx + '/login.html'",1000);
       			} else if(data.result.length == 0) { 
					$('.table-responsive').append('<div class="alert alert-warning no-result text-center" role="alert">没有找到记录 </div>');
                } else{
                	var isInterior = $("#isInterior").val();
                	console.log("isInterior:" + isInterior);
       				var datapage = data.result;
					var datalist = datapage.result;
					var totalCount = datapage.totalCount;
					var pageNum = datapage.pageNo;
					var pageSize = datapage.pageSize;
					var totalPages = datapage.totalPages;
					$(".totalCount").html(totalCount);
					$(".totalPages").html(totalPages);
					$(".pageNo").html(pageNum);
                    var tempHtml="";  
                    var ser = 1; 
                    for(var i=0;i<datalist.length;i++){   
                    	var productList = datalist[i];  
                    	tempHtml +="<tr data-id='"+productList.id+"' data-pageno='" + pageNum + "'>"; 
                    	tempHtml +="<td><div class='checkbox'><label><input type='checkbox' data-roleid="+productList.id+" name='itemCheck' value="+productList.id+" /></label></div></td>";
                    	tempHtml +="<td>"+ser+"</td>"; 
                    	tempHtml +="<td>"+isnull(productList.code)+"</td>"; 
                    	tempHtml +="<td>"+isnull(productList.barCode)+"</td>";
                    	tempHtml +="<td>"+isnumber(productList.productName)+"</td>";
                    	tempHtml +="<td>"+tradeType(productList.tradeType)+"</td>";
                    	tempHtml +="<td>"+isnull(productList.productTypeName)+"</td>";
                    	tempHtml +="<td>"+isnull(productList.brandName)+"</td>";  
                    	tempHtml +="<td>"+common.getSmpFormatDate(productList.createTime)+"</td>";
                    	tempHtml +="<td>"+shelveState(productList.shelveState)+"</td>";  
                    	tempHtml +="<td>"+auditState(productList.auditState)+"</td>";  
                    	tempHtml +="<td>";
                    	//内部供应商操作
                    	if(isInterior == 1) {
                    		tempHtml +="<button type='button' data-toggle='modal' data-id=" +productList.id+" data-target='.modal-editNews' class='btn btn-warning btn-xs updateproduct'>编辑</button>&nbsp"; 
                    		if(productList.shelveState == 1){ 
                    			tempHtml +="<button type='button' data-id="+productList.id+" data-state=2 class='btn btn-danger btn-xs update-btn'>下架</button>&nbsp";                 		
                        	}else if(productList.shelveState == 2){
                    			tempHtml +="<button type='button' data-id="+productList.id+" data-state=1 class='btn btn-success btn-xs update-btn'>上架</button>&nbsp";
                        		/*tempHtml +="<button type='button' data-id="+productList.id+" class='btn btn-primary btn-xs delete-btn'>删除</button>&nbsp;";*/
                        	}
                    		//待审核商品
                    		if(productList.auditState == 1){ 
                    			tempHtml +="<button type='button' data-toggle='modal' data-target='.modal-audit-product' data-name="+productList.productName+" data-id="+productList.id+" class='btn btn-success btn-xs audit-btn'>审核</button>&nbsp";
                    		} 
                    	}else{	//非内部供应商操作

                    	}           		
                    	tempHtml +="</td>"; 
                    	tempHtml +="</tr>";
                    	ser = ser + 1;
                    	if($('.alert-warning').length>0){
                    		$('.alert-warning').remove();
                    	}
                    }   
                    if(datalist.length === 0&&$('.alert-warning').length<=0) { 
						$('.table-responsive').append('<div class="alert alert-warning no-result text-center" role="alert">没有找到记录 </div>');
	                } 
                    $('#dataBody').html(tempHtml);
                   
                    if (reload) {
                    	reload = false;
                    	first_load = true;
    					var initPagination = function() {
    						$("#Pagination").pagination(totalCount, {
    							num_edge_entries : 1, // 边缘页数
    							num_display_entries : 4, // 主体页数
    							callback: pageselectCallback,
    							prev_text : "«",
    							next_text : "»",
    							items_per_page : pageSize, 
    							link_to : 'javascript:void(0);'
    						});
    					}();
    					/**分页e**/
                    }
				} 
			}).fail(function (err) { 
				if($('.loading')){
					$('.loading').remove();
				}
				common.alert('服务器错误！请刷新页面重试或联系管理员',"确定"); 
            });  
	}
	
	function pageselectCallback(page_index, jq) {
		if (first_load) { //第一次初始化不需要请求
			first_load = false;
			return false;
		}
		pageNum = page_index + 1;
		showProductByPage(pageNum);
	}
	/** 列表查询end **/
	
	$(document).on('click', '.audit-btn', function (e) { 
        var $this = $(this),
        parentTr = $this.parents('tr'),
        id = $this.data('id'),
        productName = $this.data('name'),
        pageno = parentTr.data('pageno'); 
        $("#auditProductForm").find("input[name='id']").val(id);
        $("#auditProductForm").find("input[name='productName']").val(productName);
    });
	
	/** 审核通过start **/
	$("#btn_audit_pass").click(function() { 
		//审核状态，1待审核，2审核通过，3审核不通过 
		audit(2); 
	});
	/**  审核通过end **/

	/** 审核不通过start **/
	$("#btn_audit_notpass").click(function() { 
		//审核状态，1待审核，2审核通过，3审核不通过 
		audit(3);
	});
	/**  审核通过end **/
		
	/**
	 * 商品审核
	 */
	function audit(auditState) {
		var id = $("#auditProductForm").find("input[name='id']").val();
		var auditOpinion = $("#auditProductForm").find("input[name='auditOpinion']").val(); 
		$.post(ctx+"/product/audit", {
				id:id,
				auditState : auditState
		},function (data) {
			var result = data.result;
			if(result!=null && result=="noauthority") {
				common.alert1('你无此权限!');
				return;
			}
			 if(result!=null && result=="againLogin") {
				 $('.commonConfirm').modal('hide');
				 common.alert1("登录过期，请重新登录");;
				 setTimeout("location.href = ctx + '/login.html'",1000);
		     }else if(result=='success'){ 
		  		 $(".modal-audit-product").modal('hide');
		         common.mySuccessModal2('提交成功');
		         showProductByPage(1); 
		  	}else{
		  		$(".errorMsg").html(data.message);
		  	}
		  },"json"); 
	}
	
	/** 新增-上传详情图start **/
	var imgName = new Array();
	var imgSrc = new Array();
	var imgFile = new Array(); 
	$(".detail-file").bind('change', function (e) { 
		if(imgSrc.length==10){
			return alert("最多只能上传10张图片");
		}
		var imgSize = this.files[0].size;  //b
		if(imgSize>1024*1024*5){//1M
			return alert("上传图片不能超过5M");
		}
		if(this.files[0].type != 'image/png' && this.files[0].type != 'image/jpeg' && this.files[0].type != 'image/gif'){
			return alert("图片上传格式不正确");
		}
		var fileList = this.files;
		for(var i = 0; i < fileList.length; i++) {
			var imgSrcI = getObjectURL(fileList[i]);
			imgName.push(fileList[i].name);
			imgSrc.push(imgSrcI);
			imgFile.push(fileList[i]);
		}
		console.log("imgSrc 长度：" + imgSrc.length);
		addNewContent(); 
	});
	
	function addNewContent() { 
		$("#detail-img-show").html("");
		for(var a = 0; a < imgSrc.length; a++) {
			var oldBox = $("#detail-img-show").html(); 
			$("#detail-img-show").html(oldBox + '<div class="preview" index="'+a+'"><img src="'+imgSrc[a]+'" alt=""><a index="'+a+'"><i class="ico-delete"></i></a></div>');
		}
		console.log($("detail-img-show").html());
	}
	
	$("#detail-img-show").on("dblclick",'.preview',function(){
    	var index = $(this).attr("index");
    	console.log("index:" + index);
		imgSrc.splice(index, 1);
		imgFile.splice(index, 1);
		imgName.splice(index, 1);
		addNewContent(); 
  });
	
	function getObjectURL(file) {
		var url = null ;
		if (window.createObjectURL!=undefined) { // basic
			url = window.createObjectURL(file) ;
		} else if (window.URL!=undefined) { // mozilla(firefox)
			url = window.URL.createObjectURL(file) ;
		} else if (window.webkitURL!=undefined) { // webkit or chrome
			url = window.webkitURL.createObjectURL(file) ;
		}
		return url ;
	} 
	
	//上传图片
	$("#upload-detail-file").on("click",function(){
		var formFile = new FormData(); 
		if(imgFile.length == 0) {
			return;
		}
		$.each(imgFile, function(i, file){
            formFile.append('file', file);
        });
		$.ajax({
            url: ctx + "/product/saveproductpic",
            type: 'POST',
            data: formFile,
            async: true,  
            cache: false,  
            contentType: false, 
            processData: false, 
            // traditional:true,
            dataType:'json',
            success: function(data) {
            	if(data.result!=null && data.result=="againLogin"){
 	         		$('.commonConfirm').modal('hide');
 	         		common.alert1("登录过期，请重新登录");
 					setTimeout("location.href = ctx + '/login.html'",1000);
             	}else if(data.result=='success'){
             		common.mySuccessModal2("上传成功"); 
             		var list = data.message;
             		var htm = "";
             		for(var i=0;i<list.length;i++){   
             			htm += "<input type='hidden' name='detailImgPaths["+i+"]' value="+list[i]+" />"
             		}
             		$("#detailImgPathInputDiv").html(htm); 
               	}else if(data.result=='fail'){
               		common.alert1("上传失败，请重试");
               	}
            }
        })
  });
	/** 新增-上传详情图end **/
	
	//清空图片缓存、清除原有信息
	$(".add").click(function() {
		console.log("清空图片缓存");
		imgNameMain.splice(0,imgNameMain.length);
		imgSrcMain.splice(0,imgSrcMain.length);
		imgFileMain.splice(0,imgFileMain.length);
	    imgName.splice(0,imgName.length);
		imgSrc.splice(0,imgSrc.length);
		imgFile.splice(0,imgFile.length);
		$(".errorMsg").html("");
		clearAddInfo(); 
	}); 
	
	/** 新增-上传主图start **/
	var imgNameMain = new Array();
	var imgSrcMain = new Array();
	var imgFileMain = new Array(); 
	$(".main-file").bind('change', function (e) { 
		if(imgSrcMain.length==4){
			return alert("最多只能上传4张图片");
		}
		var imgSizeMain = this.files[0].size;  //b
		if(imgSizeMain>1024*1024*5){//1M
			return alert("上传图片不能超过5M");
		}
		if(this.files[0].type != 'image/png' && this.files[0].type != 'image/jpeg' && this.files[0].type != 'image/gif'){
			return alert("图片上传格式不正确");
		}
		var fileList = this.files;
		for(var i = 0; i < fileList.length; i++) {
			var imgSrcI = getObjectURL(fileList[i]);
			imgNameMain.push(fileList[i].name);
			imgSrcMain.push(imgSrcI);
			imgFileMain.push(fileList[i]);
		} 
		addNewContentMain(); 
	});
	
	function addNewContentMain() { 
		$("#main-img-show").html("");
		for(var a = 0; a < imgSrcMain.length; a++) {
			var oldBox = $("#main-img-show").html(); 
			$("#main-img-show").html(oldBox + '<div class="preview" index="'+a+'"><img src="'+imgSrcMain[a]+'" alt=""><a index="'+a+'" ><i class="ico-delete"></i></a></div>');
		} 
	}
	
	$("#main-img-show").on("dblclick",'.preview',function(){
    	var index = $(this).attr("index"); 
		imgSrcMain.splice(index, 1);
		imgFileMain.splice(index, 1);
		imgNameMain.splice(index, 1);
		addNewContentMain(); 
  }); 
	
	//上传图片
	$("#upload-main-file").on("click",function(){
		var formFile = new FormData();
		console.log("imgFileMain 长度" + imgFileMain.length);
		if(imgFileMain.length == 0) {
			return;
		}
		$.each(imgFileMain, function(i, file){
            formFile.append('file', file);
        });
		$.ajax({
            url: ctx + "/product/saveproductpic",
            type: 'POST',
            data: formFile,
            async: true,  
            cache: false,  
            contentType: false, 
            processData: false, 
            // traditional:true,
            dataType:'json',
            success: function(data) {
            	if(data.result!=null && data.result=="againLogin"){
 	         		$('.commonConfirm').modal('hide');
 	         		common.alert1("登录过期，请重新登录");
 					setTimeout("location.href = ctx + '/login.html'",1000);
             	}else if(data.result=='success'){
             		common.mySuccessModal2("上传成功"); 
             		var list = data.message;
             		var htm = "";
             		for(var i=0;i<list.length;i++){   
             			htm += "<input type='hidden' name='mainImgPaths["+i+"]' value="+list[i]+" />"
             		}
             		$("#mainImgPathInputDiv").html(htm); 
               	}else if(data.result=='fail'){
               		common.alert1("上传失败，请重试");
               	}
            }
        })
  });
	/** 新增-上传主图end **/
	
	/** 添加验证start **/
	$('#addshopForm').validate({
        rules: {
            'productName': {
                required: true 
            },
            'code': {
                required: true 
            },
            'tradeType': {
                required: true
            },
            'barCode': {
                required: true
            },
            'packType': {
                required: true
            }, 
            'shelfLife': { 
                digits: true,
                number: true,
                min:0
            },
            'brandId': {
                required: true
            },
            'makeCountry': {
                required: true
            } 
        },
        messages: {
        	'productName': {
     		    required: "请填写商品名称" 
     		 },
     		'code': {
                required: "请填写商品货号" 
            },
     		'tradeType': {
                required: "请选择贸易类型"
            },
            'barCode': {
                required: "请填写条形码"
            },
            'packType': {
                required: "请选择包装类型"
            }, 
     		'shelfLife': { 
     		    digits: "请输入有效的整数",
     		    number: "请输入有效的数字",
     		     min : "不能小于0"
     		 },
     		 'brandId': {
                 required: "请选择商品品牌"
             },
             'makeCountry': {
                 required: "请填写原产地国家"
             } 
        },
        errorClass: "error",
		success: 'valid',
		unhighlight: function(element, errorClass, validClass) { //验证通过
			$(element).tooltip('destroy').removeClass(errorClass);
		}, 
		errorPlacement: function(label, element) {
			$(element).tooltip('destroy'); /*必需*/
			$(element).attr('title', $(label).text()).tooltip('show');
		},
        onclick: true 
    });
	/** 添加验证end **/
	
	/** 选择完商品分类加载分类属性s **/
	$('#countyQuery').on('click', 'a', function() { 
		var thirdroductType = $("#addshopForm").find("input[name='thirdroductType']").val();
		$.post(ctx+"/productattribute/list", {
			productTypeId : thirdroductType
		},function (data) {
			var result = data.result;
			if(result!=null && result=="noauthority") {
				common.alert1('你无此权限!');
				return;
			}
     		if(data.result!=null && data.result=="againLogin") {
         		$('.commonConfirm').modal('hide');
     			common.alert1("登录过期，请重新登录");
				setTimeout("location.href = ctx + '/login.html'",1000);
        	}else{
        		var datalist = data.list;
        		if(datalist !=null && datalist.length > 0) { 
        			$("#productAttrDiv").show();
        			$("#attr_key").html(datalist[0].attrKey + "：");
        			var tempHtml = "";
            		for(var i=0;i<datalist.length;i++){   
                    	var data = datalist[i];
                    	tempHtml += "<option data-key="+data.attrKey +" data-value="+data.attrValue +" >"+data.attrValue+"</option>";
                    }
            		$("#addshopForm").find("select[name='product_attr_sel']").html(tempHtml); 
        		}else{
        			$("#addshopForm").find("select[name='product_attr_sel']").html(""); 
        			$("#productAttrDiv").hide();
        		} 
          	}
          },"json");
	});
	/** 选择完商品分类加载分类属性e **/
	
	/** 添加start **/
	$("#btn_addshop").click(function() {
    	var isValid = $("#addshopForm").valid();  
        if (isValid) { 	 
        	if($("#mainImgPathInputDiv").find('input').length == 0) {
        		common.alert1("请先上传主图");
        		return;
        	} 
        	if($("#detailImgPathInputDiv").find('input').length == 0) {
        		common.alert1("请先上传详情图");
        		return;
        	}
        	var productType = $("#addshopForm").find("input[name='firstProductType']").val()+ "-" 
				+ $("#addshopForm").find("input[name='secondProductType']").val() + "-" 
				+ $("#addshopForm").find("input[name='thirdroductType']").val(); 
        	$("#addshopForm").find("input[name='productType']").val(productType);
        	var productTypeName = $.trim($("#EditProMenu").text())+"-"+$.trim($("#EditCityMenu").text())+"-"+$.trim($("#EditDistMenu").text()); 
        	$("#addshopForm").find("input[name='productTypeName']").val(productTypeName);
        	
        	//商品属性
        	var attrOpt = $("#productAttr-select option:selected"); 
        	var key = attrOpt.data("key");
        	var value = attrOpt.data("value");
        	console.log("key:" + key + ",value" + value);
        	if(key!="" && key!=null && key!=undefined){
        		$("#addshopForm").find("input[name='productAttr']").val(key + "：" + value);
        	} 
        	 
        	$.post(ctx + '/product/addproduct', $('#addshopForm').serialize(),function (data) {
          		if(data.result!=null && data.result=="againLogin"){
 	         		$('.commonConfirm').modal('hide');
 	         		common.alert1("登录过期，请重新登录");
 					setTimeout("location.href = ctx + '/login.html'",1000);
             	}else if(data.result=='success'){
             		$('.modal-addNews').modal('hide');
             		clearAddInfo(); 
 	          		$('.mySuccessModal1').modal({show:true,backdrop: 'static', keyboard: false});
 	      	        common.mySuccessModal1('添加成功!','如需继续添加，请点击返回继续添加','返回继续添加','前往列表',
   	        		function () {
   	        			$('.mySuccessModal1').modal('hide');  
   	        			$('.modal-addNews').modal('hide');  
   	        			showProductByPage(1);
   	        		},
   	        		function () {
   	        			imgNameMain.splice(0,imgNameMain.length);
   	        			imgSrcMain.splice(0,imgSrcMain.length);
   	        			imgFileMain.splice(0,imgFileMain.length);
   	        		    imgName.splice(0,imgName.length);
   	        			imgSrc.splice(0,imgSrc.length);
   	        			imgFile.splice(0,imgFile.length);
   	        			$(".errorMsg").html("");
   	        			$('.modal-addNews').modal('show');
   	        		});   
               	}else if(data.result=='fail'){
               		$(".errorMsg").html(data.message);
               	}else{
               		$(".errorMsg").html("信息提交错误");
               	}
               },"json"); 
        }  
	});
	/** 添加end **/
	
	
	/** 修改start **/
	$("#btn_updateshop").click(function() {
    	var isValid = $("#updateProductForm").valid();  
        if (isValid) {    
        	$.post(ctx + '/product/updateproduct', $('#updateProductForm').serialize(),function (data) {
          		if(data.result!=null && data.result=="againLogin"){
 	         		$('.commonConfirm').modal('hide');
 	         		common.alert1("登录过期，请重新登录");
 					setTimeout("location.href = ctx + '/login.html'",1000);
             	}else if(data.result=='success'){
             		$('.modal-editNews').modal('hide');
//             		clearUpdateInfo(); 
             		common.mySuccessModal2(data.message);
             		showProductByPage(1);
               	}else if(data.result=='fail'){
               		$(".errorMsg").html(data.message);
               	}else{
               		$(".errorMsg").html("信息提交错误");
               	}
               },"json"); 
        }  
	});
	/** 修改end **/
	
	//清除商品添加弹框的信息
	function clearAddInfo() {
		$('#addshopForm').find("input[name='productName']").val("");
		$('#addshopForm').find("input[name='subtitle']").val(""); 
		$('#addshopForm').find("input[name='code']").val("");
		$('#addshopForm').find("input[name='barCode']").val("");
		$('#addshopForm').find("select[name='tradeType']").val("");  
		$('#addshopForm').find("select[name='packType']").val(1); 
		$('#addshopForm').find("input[name='marketPrice']").val("");  
		$('#addshopForm').find("input[name='shelfLife']").val(""); 
		$('#addshopForm').find("select[name='brandId']").val("");  
		$('#addshopForm').find("input[name='makeCountry']").val("");
		$('#addshopForm').find("input[name='produceLabel']").val("");
		$('#addshopForm').find("input[name='warmPrompt']").val("");
		$('#addshopForm').find("input[name='content']").val(""); 
		$("#detail-img-show").html("");
		$("#main-img-show").html("");
		$("#detailImgPathInputDiv").html("");
    	$("#mainImgPathInputDiv").html(""); 
	}
	
	/*显示所有商品品牌s*/
	function showProductBrand(){
		 $.post(ctx+"/productbrand/list", {},function (data) {
			var result = data.result;
			if(result!=null && result=="noauthority") {
				common.alert1('你无此权限!');
				return;
			}
     		if(data.result!=null && data.result=="againLogin") {
         		$('.commonConfirm').modal('hide');
     			common.alert1("登录过期，请重新登录");
				setTimeout("location.href = ctx + '/login.html'",1000);
        	}else{
        		var datalist = data.productType;
        		var tempHtml = "";
        		for(var i=0;i<datalist.length;i++){   
                	var data = datalist[i];
                	tempHtml += "<option value='"+data.id+"'>"+data.brandName+"</option>";
                }
      	        $("#addshopForm").find("select[name='brandId']").append(tempHtml);
      	        $("#updateProductForm").find("select[name='brandId']").append(tempHtml);
//        		var tempHtml = "<option value=''>全部</option>";
//      	        $("select[name='role-query']").append(tempHtml); //查询下拉框
          	}
          },"json");
	}
	/*显示所有商品品牌e*/
	
	/**删除start */
	$(document).on('click', '.delete-btn', function(){
		var varId = $(this).data("id");
		var parentTr = $(this).parents('tr');
        var pageno = parentTr.data('pageno');
		$('.commonConfirm').modal('show');				
		common.commonConfirm("删除", "确定删除", "",
			function() {
            	 $.post(ctx+"/product/deleteproductbyids", {
    				 id:varId
    			 },function (data) {
    				 var result = data.result;
					 if(result!=null && result=="noauthority") {
						 common.alert1('你无此权限!');
						 return;
					 }
					 console.log("data.result:"+data.result);
    	    		 if(data.result!=null && data.result=="againLogin") {
    	    			 $('.commonConfirm').modal('hide');
    	    			 common.alert1("登录过期，请重新登录");
    					 setTimeout("location.href = ctx + '/login.html'",1000);
    	             }else if(data.result=='success'){ 
    	            	$('.commonConfirm').modal('hide');
    	     	        common.mySuccessModal2(data.message);
    	     	        showProductByPage(pageno);
    	         	}else{
    	         		console.log("else:"+data.message);
    	         		common.alert1(data.message);
    	         	}
    	         },"json"); 
			}
		);
	});
	/** 删除end **/
	
	/**上下架start */
	$(document).on('click', '.update-btn', function(){
		var varid = $(this).data("id");
        var state = $(this).data('state');
        var parentTr = $(this).parents('tr');
        var pageno = parentTr.data('pageno');
        if(state == 1){
        	var str = "上架";
		}else if(state == 2){
			var str = "下架";
		}else{
			var str = "--";
		}
		$('.commonConfirm').modal('show');
		common.commonConfirm("修改", "确定"+str+"该商品吗？", "",
			function() {
            	 $.post(ctx+"/product/updatestate", {
    				 id:varid,shelveState:state
    			 },function (data) {
    				 var result = data.result;
					 if(result!=null && result=="noauthority") {
						 common.alert1('你无此权限!');
						 return;
					 }
    	    		 if(data.result!=null && data.result=="againLogin") {
    	    			 $('.commonConfirm').modal('hide');
    	    			 common.alert1("登录过期，请重新登录");
    					 setTimeout("location.href = ctx + '/login.html'",1000);
    	             }else if(data.result=='success'){ 
    	            	$('.commonConfirm').modal('hide');
    	     	        common.mySuccessModal2(data.message);
    	     	        showProductByPage(pageno);
    	         	}else{
    	         		common.alert1(data.message);
    	         	}
    	         },"json"); 
			}
		);
	});
	/** 上下架end **/
	
	/**删除多个s*/
	$('#deleteMany').click(function(e) {
		var ids = "";
		var count = 0;
		var checks = document.getElementsByName("itemCheck");
		console.log(checks);
		for(var i=0;i<checks.length;i++){
			if(checks[i].checked){
				count++;
				ids += checks[i].value + ",";
			}
		}
		if(count<1){
			common.alert1("请至少选择一个");
		}else{
			$('.commonConfirm').modal('show');
			common.commonConfirm("删除", "确定删除", "这"+count+"个商品吗",
				function() {
	            	 $.post(ctx+"/product/deleteproductbyids", {ids:ids},
	            		function (data) {
		            		 var result = data.result;
		     				 if(result!=null && result=="noauthority") {
		     					 common.alert1('你无此权限!');
		     					 return;
		     				 }
	    		    		 if(data.result!=null && data.result=="againLogin") {
	    		    			 $('.commonConfirm').modal('hide');
	    		    			 common.alert1("登录过期，请重新登录");
	    						 setTimeout("location.href = ctx + '/login.html'",1000);
	    		             }else if(data.result=='success'){ 
	    		         		 $(".commonConfirm").modal('hide');
	    		     	         common.mySuccessModal2(data.message);
	    		     	         showProductByPage(1);
	    		         	}else{
	    		         		$(".updateMsg").html(data.message);
	    		         	}
	    		 },"json"); 
			});
		}
	});
	/**删除多个e*/
	
	/** 修改验证start **/
	$('#updateProductForm').validate({
        rules: {
            'productName': {
                required: true 
            },
            'code': {
                required: true 
            },
            'tradeType': {
                required: true
            },
            'barCode': {
                required: true
            },
            'packType': {
                required: true
            }, 
            'shelfLife': { 
                digits: true,
                number: true,
                min:0
            },
            'brandId': {
                required: true
            },
            'makeCountry': {
                required: true
            } 
        },
        messages: {
        	'productName': {
     		    required: "请填写商品名称" 
     		 },
     		'code': {
                required: "请填写商品货号" 
            },
     		'tradeType': {
                required: "请选择贸易类型"
            },
            'barCode': {
                required: "请填写条形码"
            },
            'packType': {
                required: "请选择包装类型"
            }, 
     		'shelfLife': { 
     		    digits: "请输入有效的整数",
     		    number: "请输入有效的数字",
     		     min : "不能小于0"
     		 },
     		 'brandId': {
                 required: "请选择商品品牌"
             },
             'makeCountry': {
                 required: "请填写原产地国家"
             }
        },
        errorClass: "error",
		success: 'valid',
		unhighlight: function(element, errorClass, validClass) { //验证通过
			$(element).tooltip('destroy').removeClass(errorClass);
		}, 
		errorPlacement: function(label, element) {
			$(element).tooltip('destroy'); /*必需*/
			$(element).attr('title', $(label).text()).tooltip('show');
		},
        onclick: true 
    });
	/** 修改验证end **/
	
	$(document).on('click', '.updateproduct', function (e) { 
		
		$('#provinceQueryUpdate').html('');
		$('#cityQueryUpdate').html('');
		$('#countyQueryUpdate').html(''); 
		
        var $this = $(this),
        parentTr = $this.parents('tr'),
        id = $this.data('id'),
        pageno = parentTr.data('pageno');
    	$(".updateMsg").html("");
    	$("#detailImgPathInputDiv").html("");
    	$("#mainImgPathInputDiv").html("");
    	$.getJSON(ctx + '/product/querybyid', {
    		id : id
    	}, function(data) {
    		var result = data.result;
			if(result!=null && result=="noauthority") {
				common.alert1('你无此权限!');
				return;
			}
    		if(data==null || data.length <= 0){
    			$(".updateMsg").html("数据异常,请重试");
    		}else{
    			var product = data.product;
    			var imglist = data.imglist;
    			
    			$("#updateProductForm").find("input[name='id']").val(product.id);
    			$('#updateProductForm').find("input[name='productName']").val(product.productName);
    			$('#updateProductForm').find("input[name='subtitle']").val(product.subtitle); 
    			$('#updateProductForm').find("input[name='code']").val(product.code);
    			$('#updateProductForm').find("input[name='barCode']").val(product.barCode);
    			$('#updateProductForm').find("select[name='tradeType']").val(product.tradeType);  
    			$('#updateProductForm').find("select[name='packType']").val(product.packType); 
    			$('#updateProductForm').find("input[name='marketPrice']").val(product.marketPrice);  
    			$('#updateProductForm').find("input[name='shelfLife']").val(product.shelfLife); 
    			$('#updateProductForm').find("select[name='brandId']").val(product.brandId);  
    			$('#updateProductForm').find("input[name='makeCountry']").val(product.makeCountry);
    			$('#updateProductForm').find("input[name='produceLabel']").val(product.produceLabel);
    			$('#updateProductForm').find("input[name='warmPrompt']").val(product.warmPrompt);
    			$('#updateProductForm').find("input[name='content']").val(product.content);
//    			var productType = product.productType; 
//    			var ptypes= new Array(); 
//    			ptypes = productType.split("-");
//    			console.log("ptypes[2]:"+ptypes[2]);
//    			var addrUpdate = new producttype.ProductType({
//    				initfirsttype:ptypes[0],
//    				initsecondtype:ptypes[1],
//    				initthiredtype:ptypes[2],
//    				wrapper: $('.address-group-update'),
//    				firstlevelWrapper: $('#provinceQueryUpdate'),
//    				secondlevelWrapper: $('#cityQueryUpdate'),
//    				thiredlevelWrapper: $('#countyQueryUpdate'), 
//    			}); 
    			
    			$("#detailImgPathInputDiv").html("");
    	    	$("#mainImgPathInputDiv").html(""); 
    	    	 
    	    	$("#detail-img-show-update").html("");
    			$("#main-img-show-update").html("");
    			if(imglist == null || imglist.length <= 0){
    				$('#resultupdate').html('');
    			}else{
    				var mainimghtml = "";
    				var detailimghtml = "";
    				for(var i=0;i<imglist.length;i++){
    					var productimg = imglist[i];
    					if(productimg.type == 1){	//主图
    						mainimghtml += '<div class="preview" ><img src="'+ctx + productimg.imgPath+'" alt=""><a ><i class="ico-delete"></i></a></div>';
    					}else{	//副图
    						detailimghtml += '<div class="preview" ><img src="'+ctx + productimg.imgPath+'" alt=""><a ><i class="ico-delete"></i></a></div>';
    					}
    				}
    				console.log("mainimghtml:"+mainimghtml);
    				console.log("detailimghtml:"+detailimghtml);
    				$("#main-img-show-update").html(mainimghtml);
    				$("#detail-img-show-update").html(detailimghtml);
//    				for(var a = 0; a < imgSrcMain.length; a++) {
//    					var oldBox = $("#main-img-show").html(); 
//    					$("#main-img-show").html(oldBox + '<div class="preview" index="'+a+'"><img src="'+imgSrcMain[a]+'" alt=""><a index="'+a+'" ><i class="ico-delete"></i></a></div>');
//    				} 
    				
//    				$('#resultupdate').html(imghtml2);
//    				$('#updateProductForm .mainshow').html(imghtml1);
    			}
    			$("#updateImgIds").val('');
//    			imgupload();
    		}
    	});
    });

	/** 修改start **/
	$("#btn_updateProduct").click(function() {
    	var isValid = $("#updateProductForm").valid();
        if (isValid) { 	
        	var formData = new FormData($("#updateProductForm")[0]);
       	 	$.ajax({  
    			type : "post",  
    	        async:false,  
    	        url : ctx + "/product/updateproduct",  
    	        data : formData,
    	        dataType : "json",//数据类型为json  
    	        processData : false,  //必须false才会避开jQuery对 formdata 的默认处理   
    	        contentType : false,  //必须false才会自动加上正确的Content-Type
    	        success : function(data){ 
    	        	var result = data.result;
	   				if(result!=null && result=="noauthority") {
	   					common.alert1('你无此权限!');
	   					return;
	   				}
	   				if(data.result!=null && data.result=="againLogin") {
	   	    			 $('.commonConfirm').modal('hide');
	   	    			 common.alert1("登录过期，请重新登录");
	   					 setTimeout("location.href = ctx + '/login.html'",1000);
  	             	}else if(data.result=='success'){ 
  	             		 $("#updateImgIds").val('');
  	             		 $(".modal-editNews").modal('hide');
  	         	         common.mySuccessModal2(data.message);
  	         	         var pageno = $("#updateProductForm").find("input[name='pageno']").val();
  	         	         showProductByPage(pageno);
	             	}else{
	             		$(".updateMsg").html(data.message);
	             	}
	    	    },  
    	        error:function(){  
    	        	console.log('fail');  
    	        }  
	    	 });
        }  
	});
	/** 修改end **/
	
	function imgupload(){
		var productId = $("#productId").val();
		$.Tupload.init({
			url: "product/saveproductpic?productId=" + productId,
			title	  : "宝贝图片大小不能超过500kb,为使避免图片上传出现问题，请尽量选择完毕图片后再上传",
			fileNum: 8, // 上传文件数量
			divId: "T_upload", // div  id
			accept: "image/jpeg,image/x-png", // 上传文件的类型
			fileSize  :51200000,     // 上传文件的大小
			onSuccess: function(data, i) {
				var temp =eval('(' + data.currentTarget.response + ')')
				if(temp.fileName != undefined){
					$("#img_src"+i).attr('value',temp.fileName);
					$("#img_src"+i).attr('name',"upload_img");
				}
			},
			onDelete: function(i) {
				var img_val = $("#img_src"+i).attr("value");
				if(img_val != '' && img_val != undefined){
					var md = "product";
					var img= $.page.getImgUrl(img_val);
					$.ajax({
						type:"POST",
						url: "base/delPic" ,
						data : {img:img,id: pid,md:md},
						success: function(rel){}
					});
				}
			}
		});
	}
	
	function isnull(value) {
		if (value == null || value == '' || typeof (value) == "undefined")
			return "--";
		else
			return value;
	}

	/*上下架状态，1上架，2下架*/  
	function shelveState(value) {
		if (value == null || value == ''){
			return "未知";
		}else if(value == 1) {
			return "<span style='color:green'>上架中</span>";
		}else if(value == 2) {
			return "<span style='color:red'>下架中</span>";
		} 
	}
	
	/*贸易类型，1保税直供，2国内发货，3海外直邮，4海外交货*/
	
	function tradeType(value) {
		if (value == null || value == ''){
			return "未知";
		}else if(value == 1) {
			return "保税直供";
		}else if(value == 2) {
			return "国内发货";
		} else if(value == 3) {
			return "海外直邮";
		} else if(value == 4) {
			return "海外交货";
		} 
	}
	
	/*审核状态，1待审核，2审核通过，3不通过*/
	function auditState(value) {
		if (value == null || value == ''){
			return "未知";
		}else if(value == 1) {
			return "<span style='color:red'>待审核</span>";
		}else if(value == 2) {
			return "<span style='color:green'>审核通过</span>";
		} else if(value == 3) {
			return "不通过";
		} 
	}
	
	
	
	function isnumber(value) {
		if (value == null || value == '')
			return "0.00";
		else
			return value;
	}
	
	$("#addshopForm").on('change','.mainImg',function(e){
		for (var i = 0; i < e.target.files.length; i++) {    
	        var file = e.target.files.item(i); 
	        if (!(/^image\/.*$/i.test(file.type))) {    
	            common.alert1("您选择的不是图片，请重新选择");
	            $("#addshopForm .#mainImg").val('');
	            $("#addshopForm .mainshow").html('');
	            return;
	        }    
	        //实例化FileReader API    
	        var freader = new FileReader();    
	        freader.readAsDataURL(file);    
	        freader.onload = function(e) {    
	        	$("#addshopForm .mainshow").html('<img style="height: 90px" src="' + e.target.result +'" alt="" />&nbsp;&nbsp;&nbsp;');
	        }    
	    }
	});
	
	$("#updateProductForm").on('change','.mainImg',function(e){
		for (var i = 0; i < e.target.files.length; i++) {    
	        var file = e.target.files.item(i); 
	        if (!(/^image\/.*$/i.test(file.type))) {    
	            common.alert1("您选择的不是图片，请重新选择");
	            $("#updateProductForm .#mainImg").val('');
	            $("#updateProductForm .mainshow").html('');
	            return;
	        }    
	        //实例化FileReader API    
	        var freader = new FileReader();    
	        freader.readAsDataURL(file);    
	        freader.onload = function(e) {    
	        	$("#updateProductForm .mainshow").html('<img style="height: 90px" src="' + e.target.result +'" alt="" />&nbsp;&nbsp;&nbsp;');
	        }    
	    }
	});
	
});

function removeImg(t) {
	var o=document.getElementById("resultupdate");//获取父节点
	var a=document.getElementById(t);//获取需要删除的子节点
	o.removeChild(a)//从父节点o上面移除子节点a
	var ids = $("#updateImgIds").val() + t+",";
	$("#updateImgIds").val(ids);
} 
/*e*/

